<template>
  <div class="admin-order-manage">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <div class="search-container">
        <div class="search-row">
          <div class="search-item">
            <label>商品名称：</label>
            <el-input 
              v-model="searchParams.productName" 
              placeholder="请输入商品名称" 
              clearable
              style="width: 200px;">
            </el-input>
          </div>
          
          <div class="search-item">
            <label>订单状态：</label>
            <div class="filter-buttons">
              <el-button 
                :type="searchParams.status === '' ? 'primary' : ''" 
                size="small"
                @click="searchParams.status = ''">
                全部
              </el-button>
              <el-button 
                :type="searchParams.status === '待发货' ? 'primary' : ''" 
                size="small"
                @click="searchParams.status = '待发货'">
                待发货
              </el-button>
              <el-button 
                :type="searchParams.status === '已发货' ? 'primary' : ''" 
                size="small"
                @click="searchParams.status = '已发货'">
                已发货
              </el-button>
              <el-button 
                :type="searchParams.status === '已收货' ? 'primary' : ''" 
                size="small"
                @click="searchParams.status = '已收货'">
                已收货
              </el-button>
            </div>
          </div>
          
          <div class="search-item">
            <label>时间范围：</label>
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 380px;">
            </el-date-picker>
          </div>
          
          <div class="search-actions">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            <el-button type="warning" icon="el-icon-download" @click="handleExport">导出Excel</el-button>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 订单列表 -->
    <el-card class="table-card">
      <div class="table-header">
        <h3>订单列表</h3>
        <span class="total-count">共 {{ total }} 条数据</span>
      </div>
      
      <el-table 
        :data="orderList" 
        v-loading="loading"
        stripe
        style="width: 100%">
        <el-table-column prop="id" label="订单ID" min-width="80" align="center"></el-table-column>
        
        <el-table-column prop="orderNo" label="订单编号" min-width="160">
          <template slot-scope="scope">
            <span style="font-weight: 600; color: #303133;">{{ scope.row.orderNo }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="商品图片" min-width="150" align="center">
          <template slot-scope="scope">
            <div class="image-stack" v-if="getOrderImages(scope.row.details).length > 0" @click="handleViewImages(scope.row)">
              <img 
                v-for="(img, index) in getOrderImages(scope.row.details).slice(0, 3)" 
                :key="index"
                :src="img" 
                :style="{ zIndex: 3 - index, left: index * 8 + 'px' }"
                class="stack-image">
              <span v-if="getOrderImages(scope.row.details).length > 3" class="image-count">+{{ getOrderImages(scope.row.details).length - 3 }}</span>
            </div>
            <span v-else style="color: #999;">暂无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column label="商品信息" min-width="250">
          <template slot-scope="scope">
            <div v-for="(detail, index) in scope.row.details" :key="index" class="product-info">
              <span style="color: #606266;">{{ detail.productName }}</span>
              <span style="color: #909399; font-size: 12px; margin-left: 8px;">x{{ detail.quantity }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="totalAmount" label="订单金额" min-width="110" align="center">
          <template slot-scope="scope">
            <span style="color: #f56c6c; font-weight: 600;">¥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="收货信息" min-width="200">
          <template slot-scope="scope">
            <div style="line-height: 1.6;">
              <div><span style="font-weight: 500;">{{ scope.row.receiverName }}</span> {{ scope.row.receiverPhone }}</div>
              <div style="color: #909399; font-size: 12px;">{{ scope.row.receiverAddress }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="订单状态" min-width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)" 
              size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="下单时间" min-width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" min-width="240" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="handleViewDetail(scope.row)">查看详情</el-button>
            <el-button 
              v-if="scope.row.status === '待发货'"
              type="text" 
              icon="el-icon-sold-out" 
              style="color: #67c23a;"
              @click="handleShip(scope.row)">
              发货
            </el-button>
            <el-button 
              v-if="scope.row.status === '待发货'"
              type="text" 
              icon="el-icon-delete" 
              style="color: #f56c6c;" 
              @click="handleCancel(scope.row)">
              取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog 
      title="订单详情" 
      :visible.sync="detailDialogVisible" 
      width="900px"
      :close-on-click-modal="false">
      <div v-if="currentOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <h4 class="section-title">订单信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">订单编号：</span>
                <span class="info-value">{{ currentOrder.orderNo }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">订单状态：</span>
                <el-tag :type="getStatusType(currentOrder.status)" size="small">{{ currentOrder.status }}</el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">下单时间：</span>
                <span class="info-value">{{ formatDate(currentOrder.createTime) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">订单金额：</span>
                <span class="info-value" style="color: #f56c6c; font-weight: 600;">¥{{ currentOrder.totalAmount }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 收货信息 -->
        <div class="detail-section">
          <h4 class="section-title">收货信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">收货人：</span>
                <span class="info-value">{{ currentOrder.receiverName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span class="info-value">{{ currentOrder.receiverPhone }}</span>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="info-item">
                <span class="info-label">收货地址：</span>
                <span class="info-value">{{ currentOrder.receiverAddress }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 商品信息 -->
        <div class="detail-section">
          <h4 class="section-title">商品信息</h4>
          <el-table :data="currentOrder.details" border stripe>
            <el-table-column label="商品图片" min-width="100" align="center">
              <template slot-scope="scope">
                <img 
                  v-if="scope.row.productImage" 
                  :src="scope.row.productImage" 
                  class="product-image"
                  @click="handlePreviewSingleImage(scope.row.productImage)">
                <span v-else style="color: #999;">暂无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="200"></el-table-column>
            <el-table-column prop="price" label="单价" min-width="100" align="center">
              <template slot-scope="scope">
                <span style="color: #f56c6c;">¥{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" min-width="80" align="center"></el-table-column>
            <el-table-column label="小计" min-width="120" align="center">
              <template slot-scope="scope">
                <span style="color: #f56c6c; font-weight: 600;">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="currentOrder && currentOrder.status === '待发货'"
          type="success" 
          icon="el-icon-sold-out"
          @click="handleShipInDialog">
          发货
        </el-button>
        <el-button 
          v-if="currentOrder && currentOrder.status === '待发货'"
          type="danger" 
          icon="el-icon-delete"
          @click="handleCancelInDialog">
          取消订单
        </el-button>
      </div>
    </el-dialog>
    
    <!-- 图片预览对话框 -->
    <el-dialog 
      title="图片预览" 
      :visible.sync="imagePreviewVisible" 
      width="800px"
      :close-on-click-modal="true">
      <div class="image-preview-container">
        <div class="preview-main">
          <i class="el-icon-arrow-left preview-arrow" @click="handlePrevImage" v-if="previewImages.length > 1"></i>
          <img :src="previewImages[currentImageIndex]" class="preview-image">
          <i class="el-icon-arrow-right preview-arrow" @click="handleNextImage" v-if="previewImages.length > 1"></i>
        </div>
        <div class="preview-footer">
          <span>{{ currentImageIndex + 1 }} / {{ previewImages.length }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminOrderList, getAdminOrderDetail, adminCancelOrder, shipOrder, exportOrders } from '@/api/adminOrder';

export default {
  name: 'AdminOrderManage',
  data() {
    return {
      // 搜索参数
      searchParams: {
        page: 1,
        size: 10,
        status: '',
        productName: '',
        startTime: '',
        endTime: ''
      },
      
      // 日期范围
      dateRange: null,
      
      // 订单列表
      orderList: [],
      total: 0,
      loading: false,
      
      // 详情对话框
      detailDialogVisible: false,
      currentOrder: null,
      
      // 图片预览
      imagePreviewVisible: false,
      previewImages: [],
      currentImageIndex: 0
    };
  },
  
  created() {
    this.loadOrderList();
  },
  
  methods: {
    /**
     * 加载订单列表
     */
    async loadOrderList() {
      this.loading = true;
      try {
        const response = await getAdminOrderList(this.searchParams);
        
        if (response.data.success) {
          const pageData = response.data.data;
          this.orderList = pageData.records || [];
          this.total = pageData.total || 0;
        } else {
          this.$notify({
            title: '错误',
            message: response.data.message || '加载订单列表失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载订单列表失败',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 获取订单商品图片列表
     */
    getOrderImages(details) {
      if (!details || details.length === 0) return [];
      return details.map(detail => detail.productImage).filter(img => img);
    },
    
    /**
     * 获取订单状态类型
     */
    getStatusType(status) {
      const typeMap = {
        '待发货': 'warning',
        '已发货': 'primary',
        '已收货': 'success'
      };
      return typeMap[status] || 'info';
    },
    
    /**
     * 查看图片
     */
    handleViewImages(row) {
      this.previewImages = this.getOrderImages(row.details);
      if (this.previewImages.length > 0) {
        this.currentImageIndex = 0;
        this.imagePreviewVisible = true;
      }
    },
    
    /**
     * 预览单张图片
     */
    handlePreviewSingleImage(imageUrl) {
      this.previewImages = [imageUrl];
      this.currentImageIndex = 0;
      this.imagePreviewVisible = true;
    },
    
    /**
     * 上一张图片
     */
    handlePrevImage() {
      if (this.currentImageIndex > 0) {
        this.currentImageIndex--;
      } else {
        this.currentImageIndex = this.previewImages.length - 1;
      }
    },
    
    /**
     * 下一张图片
     */
    handleNextImage() {
      if (this.currentImageIndex < this.previewImages.length - 1) {
        this.currentImageIndex++;
      } else {
        this.currentImageIndex = 0;
      }
    },
    
    /**
     * 搜索
     */
    handleSearch() {
      // 处理时间范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.searchParams.startTime = this.dateRange[0];
        this.searchParams.endTime = this.dateRange[1];
      } else {
        this.searchParams.startTime = '';
        this.searchParams.endTime = '';
      }
      
      this.searchParams.page = 1;
      this.loadOrderList();
    },
    
    /**
     * 重置
     */
    handleReset() {
      this.searchParams = {
        page: 1,
        size: 10,
        status: '',
        productName: '',
        startTime: '',
        endTime: ''
      };
      this.dateRange = null;
      this.loadOrderList();
    },
    
    /**
     * 查看订单详情
     */
    async handleViewDetail(row) {
      this.detailDialogVisible = true;
      
      try {
        const response = await getAdminOrderDetail(row.id);
        if (response.data.success) {
          this.currentOrder = response.data.data;
        } else {
          this.$notify({
            title: '错误',
            message: response.data.message || '加载订单详情失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载订单详情失败',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    /**
     * 发货
     */
    handleShip(row) {
      this.$confirm('确定要对该订单进行发货操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await shipOrder(row.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '发货成功',
              type: 'success',
              duration: 2000
            });
            // 刷新列表
            this.loadOrderList();
          } else {
            this.$notify({
              title: '错误',
              message: response.data.message || '发货失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '发货失败',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    /**
     * 取消订单
     */
    handleCancel(row) {
      this.$confirm('确定要取消该订单吗？订单取消后将删除相关数据。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await adminCancelOrder(row.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '订单已取消',
              type: 'success',
              duration: 2000
            });
            // 刷新列表
            this.loadOrderList();
          } else {
            this.$notify({
              title: '错误',
              message: response.data.message || '取消订单失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '取消订单失败',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    /**
     * 在详情对话框中发货
     */
    handleShipInDialog() {
      this.$confirm('确定要对该订单进行发货操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await shipOrder(this.currentOrder.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '发货成功',
              type: 'success',
              duration: 2000
            });
            // 关闭对话框并刷新列表
            this.detailDialogVisible = false;
            this.loadOrderList();
          } else {
            this.$notify({
              title: '错误',
              message: response.data.message || '发货失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '发货失败',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    /**
     * 在详情对话框中取消订单
     */
    handleCancelInDialog() {
      this.$confirm('确定要取消该订单吗？订单取消后将删除相关数据。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await adminCancelOrder(this.currentOrder.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '订单已取消',
              type: 'success',
              duration: 2000
            });
            // 关闭对话框并刷新列表
            this.detailDialogVisible = false;
            this.loadOrderList();
          } else {
            this.$notify({
              title: '错误',
              message: response.data.message || '取消订单失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '取消订单失败',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    /**
     * 导出Excel
     */
    handleExport() {
      // 处理时间范围
      let startTime = '';
      let endTime = '';
      if (this.dateRange && this.dateRange.length === 2) {
        startTime = this.dateRange[0];
        endTime = this.dateRange[1];
      }
      
      const params = {
        status: this.searchParams.status,
        productName: this.searchParams.productName,
        startTime: startTime,
        endTime: endTime
      };
      
      const exportUrl = exportOrders(params);
      window.open(exportUrl, '_blank');
      
      this.$notify({
        title: '提示',
        message: '正在导出，请稍候...',
        type: 'info',
        duration: 2000
      });
    },
    
    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.searchParams.size = size;
      this.searchParams.page = 1;
      this.loadOrderList();
    },
    
    /**
     * 当前页改变
     */
    handleCurrentChange(page) {
      this.searchParams.page = page;
      this.loadOrderList();
    },
    
    /**
     * 格式化日期
     */
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hour = String(d.getHours()).padStart(2, '0');
      const minute = String(d.getMinutes()).padStart(2, '0');
      const second = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }
  }
};
</script>

<style scoped>
.admin-order-manage {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 40px);
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  height: 120px;
}

.search-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-item label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.search-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* 表格卡片 */
.table-card {
  border-radius: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.total-count {
  color: #666;
  font-size: 14px;
}

/* 商品信息 */
.product-info {
  padding: 4px 0;
  line-height: 1.6;
}

/* 图片层叠展示 */
.image-stack {
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 auto;
  cursor: pointer;
}

.stack-image {
  position: absolute;
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s;
}

.stack-image:hover {
  transform: translateY(-5px);
}

.image-count {
  position: absolute;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  z-index: 10;
}

/* 订单详情 */
.order-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #2c5f2d;
  color: #2c5f2d;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  margin-bottom: 12px;
  line-height: 1.8;
}

.info-label {
  color: #666;
  font-weight: 500;
  margin-right: 8px;
}

.info-value {
  color: #303133;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.1);
}

/* 图片预览 */
.image-preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-main {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 500px;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-arrow {
  position: absolute;
  font-size: 30px;
  color: #409eff;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 50%;
  transition: all 0.3s;
}

.preview-arrow:hover {
  background: #409eff;
  color: #fff;
}

.preview-arrow.el-icon-arrow-left {
  left: 20px;
}

.preview-arrow.el-icon-arrow-right {
  right: 20px;
}

.preview-footer {
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框 */
.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-actions {
    margin-left: 0;
    width: 100%;
    flex-wrap: wrap;
  }
}
</style>

